package drive.RemakeService.ServiceFormat;



import com.google.gson.Gson;
import drive.Mapper.*;
import drive.Model.*;

import drive.RemakeService.ServiceInterface.UserProfileService;
import drive.pojo.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class UserProfileServiceA implements UserProfileService {

    @Value("${official.account.id}")
    private int OFFICIAL_ACCOUNT_ID; // 官方账号ID，从配置文件中获取
    Gson gson = new Gson();

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ChatSessionMapper chatSessionMapper;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private FavoriteRecordMapper favoriteRecordMapper;

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Autowired
    private FollowRelationMapper followRelationMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private SecondHandItemMapper secondHandItemMapper;

    @Autowired
    private RoadDisasterMapper roadDisasterMapper;
    @Override
    @Transactional
    public String registerUser(User user) {
        // 实现用户注册逻辑

        User find = userMapper.selectUserByUsername(user.getUsername());
        if(find==null){
            User emailCheck = userMapper.selectUserByEmail(user.getEmail());
            if(emailCheck==null){
                user.setCreditScore(500);
                user.setCreateTime(new Date());
                user.setStatus(User.Status.normal);
                userMapper.insertUser(user);
                ChatSession chatSession = new ChatSession();
                chatSession.setUser1ID(OFFICIAL_ACCOUNT_ID);
                chatSession.setUser2ID(user.getUserID());
                chatSession.setCreationTime(new Date());
                chatSession.setUpdateTime(new Date());
                chatSessionMapper.add(chatSession);
                return "User created successfully with ID: " + user.getUserID();
            }
            return "email is already registered";
        }
        return "Username is already created";
    }

    @Override
    public String loginUser(String username, String password) {
        // 实现用户登录逻辑
        User user = userMapper.selectUserByUsernameAndPassword(username,password);

        if(user == null){
            return "账号或密码错误";
        }

        if(user.getStatus()== User.Status.normal){

            Map<String,Object> map = new HashMap<>();
            String token = JwtUtils.GenJwt(user.getUserID(),"user");
            map.put("user",user);
            map.put("token",token);
            return gson.toJson(map);
        }else{
            return "账号已封禁";
        }

    }

    @Override
    public String loginUserAdmin(String username, String password) {
        // 实现用户登录逻辑
        User user = userMapper.selectUserByUsernameAndPassword(username,password);

        if(user == null){
            return "账号或密码错误";
        }

        if(user.getStatus()== User.Status.admin){

            Map<String,Object> map = new HashMap<>();
            String token = JwtUtils.GenJwt(user.getUserID(),"user");
            map.put("user",user);
            map.put("token",token);
            return gson.toJson(map);
        }else{
            return "账号已封禁";
        }

    }

    @Override
    public String updateUserProfile(User user) {
        // 获取当前用户的ID
        Integer currentUserId = user.getUserID();

        // 检查新的用户名是否被其他用户占用
        User existingUserByUsername = userMapper.selectUserByUsername(user.getUsername());
        if (existingUserByUsername != null && !(existingUserByUsername.getUserID()==currentUserId)) {
            return "用户名已存在";
        }

        // 检查新的邮箱是否被其他用户占用
        User existingUserByEmail = userMapper.selectUserByEmail(user.getEmail());
        if (existingUserByEmail != null && !(existingUserByEmail.getUserID()==currentUserId)) {
            return "邮箱已存在";
        }

        // 如果用户名和邮箱都未被其他用户占用，则更新用户资料
        userMapper.updateUser(user);
        return "个人资料更新成功";

    }

    @Override
    public String viewUserCollections(Integer userID,int PageNum,int PageSize) {
        // 实现查看收藏内容逻辑
        int PageInit = (PageNum-1)*PageSize;
        List<FavoriteRecord> list = favoriteRecordMapper.findPaginated(userID,PageInit,PageSize);
        List<Article> articleList = new ArrayList<>();
        for (FavoriteRecord favoriteRecord : list) {
            Article article = articleMapper.findById(favoriteRecord.getContentID());
            articleList.add(article);
        }
        return gson.toJson(articleList);
    }

    @Override
    public String viewUserMessages(Integer userID) {
        // 实现查看消息逻辑

        return "查看消息成功";
    }


    @Override
    @Transactional
    public String followUser(String token, Integer targetUserID) {
        // 实现关注用户逻辑
        System.out.println(1);
        int userID = JwtUtils.getuserID(token);
        if(followRelationMapper.findByFollowerAndFollowed(userID,targetUserID)!=null){
            return "已关注";
        }
        FollowRelation followRelation = new FollowRelation();
        followRelation.setFollowerID(userID);
        followRelation.setFollowedID(targetUserID);
        followRelation.setCreateTime(new Date());
        followRelationMapper.add(followRelation);
        User user = userMapper.selectUserById(userID);
        this.sendOfficialMessage(targetUserID,"userID="+user.getUserID()+",关注了你");

        return "关注用户成功";
    }

    @Override
    public String viewUserPublishedArticles(Integer userID, int PageNum, int PageSize) {
        // 实现查看已发布文章逻辑
        int PageInit = (PageNum-1)*PageSize;
        List<Article> list = articleMapper.findPaginatedByUserID(userID,PageInit,PageSize);
        return gson.toJson(list);
    }

    @Override
    public String modifyUserPublishedArticle(Article article) {
        // 实现修改已发布文章逻辑
        articleMapper.update_mini(article);
        return "修改已发布文章成功";
    }
    @Override
    public String getFollowCount(int userId) {
        int count = followRelationMapper.getFollowerCount(userId);
        return "{\"userId\":" + userId + ",\"followCount\":" + count + "}";
    }
    @Override
    public String getFollowingCount(int userId) {
        int count = followRelationMapper.getFollowingCount(userId);
        return "{\"userId\":" + userId + ",\"followingCount\":" + count + "}";
    }
    //跟关注的用户发送消息
    private void sendOfficialMessage(int followedId, String messageContent) {
        ChatSession chatSession = chatSessionMapper.findByUserIDs(OFFICIAL_ACCOUNT_ID,followedId);

        if(chatSession == null){
            // 创建会话
            chatSession = new ChatSession();
            chatSession.setUser1ID(OFFICIAL_ACCOUNT_ID);
            chatSession.setUser2ID(followedId);
            chatSession.setCreationTime(new Date());
            chatSessionMapper.add(chatSession);
            System.out.println(chatSession);
        }
        System.out.println("发送关注消息中");
        // 发送消息
        chatSession.setUpdateTime(new Date());
        chatSessionMapper.update(chatSession);
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setChatSessionID(chatSession.getChatSessionID());
        chatMessage.setSenderID(OFFICIAL_ACCOUNT_ID);
        chatMessage.setContent(messageContent);
        chatMessage.setSendTime(new Date());
        chatMessage.setStatus(ChatMessage.Status.sending);
        chatMessageMapper.add(chatMessage);

        chatSessionMapper.update_time(chatSession.getChatSessionID());
    }
    @Override
    public String getUserInfo(int userId) {
        User user = userMapper.selectUserById(userId);
        return gson.toJson(user);
    }
    @Override
    public String unfollow(int followerId, int followedId) {
        FollowRelation followRelation = followRelationMapper.findByFollowerAndFollowed(followerId, followedId);
        if (followRelation == null) {
            return "{\"status\":\"error\",\"message\":\"尚未关注该用户\"}";
        }

        followRelationMapper.delete(followerId, followedId);
        return "{\"status\":\"success\",\"message\":\"取消关注成功\"}";
    }
    @Override
    public String getUserArticleCount(int userId) {
        int count = articleMapper.countPublishedArticlesByUser(userId);
        return gson.toJson("{\"userId\":" + userId + ",\"publishedArticleCount\":" + count + "}");
    }

    /**
     * 获取文章的收藏数量和评论数量
     * @param articleId 文章ID
     * @return 包含文章ID、收藏数量和评论数量的JSON字符串
     */
    @Override
    public String getArticleStats(int articleId) {
        // 获取文章的收藏数量
        int favoriteCount = favoriteRecordMapper.countByArticleId(articleId);
        // 获取文章的评论数量
        int commentCount = commentMapper.countByArticleId(articleId);

        // 使用Gson将结果格式化为JSON字符串
        return gson.toJson("{"
                + "\"articleId\":" + articleId + ","
                + "\"favoriteCount\":" + favoriteCount + ","
                + "\"commentCount\":" + commentCount
                + "}");
    }

    /**
     * 获取用户参与的所有聊天室
     * @param userId 用户ID
     * @return 包含聊天室信息的JSON字符串
     */
    @Override
    public String getUserChatRooms(int userId) {
        List<ChatSession> chatSessions = chatSessionMapper.findByUserId(userId);
        return gson.toJson(chatSessions);
    }

    /**
     * 创建聊天室
     * @param user1ID 用户1的ID
     * @param user2ID 用户2的ID
     * @return 包含聊天室信息的JSON字符串
     */
    @Override
    @Transactional
    public String createChatRoom(int user1ID, int user2ID) {
        // 检查是否已经存在聊天室
        ChatSession existingChatSession = chatSessionMapper.findByUserIDs(user1ID, user2ID);
        if (existingChatSession != null) {
            return gson.toJson("{\"status\":\"error\",\"message\":\"聊天室已存在\"}");
        }

        // 创建新的聊天室
        ChatSession chatSession = new ChatSession();
        chatSession.setUser1ID(user1ID);
        chatSession.setUser2ID(user2ID);
        chatSession.setCreationTime(new Date());
        chatSession.setUpdateTime(new Date());
        chatSessionMapper.add(chatSession);

        return gson.toJson("{\"status\":\"success\",\"chatSession\":" + gson.toJson(chatSession) + "}");
    }

    /**
     * 获取聊天室的第一条消息
     * @param chatRoomId 聊天室ID
     * @return 包含第一条消息信息的JSON字符串
     */
    @Override
    public String getFirstMessage(int chatRoomId) {
        ChatMessage firstMessage = chatMessageMapper.findFirstMessageByChatRoomId(chatRoomId);
        if (firstMessage == null) {
            return gson.toJson("{\"status\":\"error\",\"message\":\"聊天室中没有消息\"}");
        }
        return gson.toJson("{\"status\":\"success\",\"firstMessage\":" + gson.toJson(firstMessage) + "}");
    }

    @Transactional
    @Override
    public String sendMessage(int chatRoomId, int senderId, String content) {
        // 创建消息对象
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setChatSessionID(chatRoomId);
        chatMessage.setSenderID(senderId);
        chatMessage.setContent(content);
        chatMessage.setSendTime(new Date());
        chatMessage.setStatus(ChatMessage.Status.sending);

        // 插入消息到数据库
        chatMessageMapper.add(chatMessage);
        chatSessionMapper.update_time(chatRoomId);
        return gson.toJson("{\"status\":\"success\",\"message\":\"消息发送成功\"}");
    }

    /**
     * 分页获取聊天室内的消息
     * @param chatRoomId 聊天室ID
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 包含消息列表和分页信息的JSON字符串
     */
    @Override
    public String getChatRoomMessages(int chatRoomId, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;

        List<ChatMessage> messages = chatMessageMapper.getMessagesByChatRoomId(chatRoomId, offset, pageSize);
        int totalMessages = chatMessageMapper.countMessagesByChatRoomId(chatRoomId);

        return gson.toJson("{"
                + "\"status\":\"success\","
                + "\"messages\":" + gson.toJson(messages) + ","
                + "\"totalMessages\":" + totalMessages + ","
                + "\"pageNum\":" + pageNum + ","
                + "\"pageSize\":" + pageSize
                + "}");
    }
    /**
     * 将聊天室中的所有消息标记为已读
     * @param chatRoomId 聊天室ID
     * @param userId 用户ID
     * @return 操作结果的JSON字符串
     */
    @Transactional
    @Override
    public String markAllMessagesAsRead(int chatRoomId, int userId) {
        // 更新消息状态为已读
        int updatedCount = chatMessageMapper.updateMessagesStatusAsRead(chatRoomId, userId);

        return gson.toJson("{"
                + "\"status\":\"success\","
                + "\"message\":\"成功将" + updatedCount + "条消息标记为已读\","
                + "\"timestamp\":\"" + new Date() + "\""
                + "}");
    }
    /**
     * 获取用户发布的所有二手物品
     * @param userId 用户ID
     * @return 包含二手物品信息的JSON字符串
     */
    @Override
    public String getUserSecondHandItems(int userId) {
        List<Secondhanditem> items = secondHandItemMapper.findBySellerID(userId);
        return gson.toJson(items);
    }

    /**
     * 获取用户上报的所有灾害
     * @param userId 用户ID
     * @return 包含灾害信息的JSON字符串
     */
    @Override
    public String getUserDisasters(int userId) {
        List<RoadDisaster> disasters = roadDisasterMapper.findByUserID(userId);
        return gson.toJson(disasters);
    }

    @Override
    public String viewItemCollections(Integer userID,int PageNum,int PageSize) {
        // 实现查看收藏内容逻辑
        int PageInit = (PageNum-1)*PageSize;
        List<FavoriteRecord> list = favoriteRecordMapper.findPageItem(userID,PageInit,PageSize);
        List<Secondhanditem> articleList = new ArrayList<>();
        for (FavoriteRecord favoriteRecord : list) {
            Secondhanditem secondhanditem = secondHandItemMapper.findByItemID(favoriteRecord.getContentID());
            articleList.add(secondhanditem);
        }
        return gson.toJson(articleList);
    }

    /**
     * 分页获取用户关注的人的文章列表
     * @param userId 用户ID
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 包含文章列表和分页信息的JSON字符串
     */
    @Override
    public String getFollowedUsersArticles(int userId, int pageNum, int pageSize) {
        List<Integer> followedUserIds = followRelationMapper.getFollowedUserIds(userId);
        if (followedUserIds.isEmpty()) {
            return gson.toJson("{\"status\":\"error\",\"message\":\"您尚未关注任何用户\"}");
        }

        int offset = (pageNum - 1) * pageSize;
        List<Article> articles = articleMapper.getArticlesByAuthorIds(followedUserIds, offset, pageSize);
        int total = articleMapper.getArticlesCountByAuthorIds(followedUserIds);

        return gson.toJson("{"
                + "\"status\":\"success\","
                + "\"data\":" + gson.toJson(articles) + ","
                + "\"total\":" + total + ","
                + "\"pageNum\":" + pageNum + ","
                + "\"pageSize\":" + pageSize
                + "}");
    }

    /**
     * 获取用户关注的用户信息
     * @param userId 用户ID
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 包含关注用户信息和分页信息的JSON字符串
     */
    @Override
    public String getFollowedUsers(int userId, int pageNum, int pageSize) {
        List<Integer> followedUserIds = followRelationMapper.getFollowedUserIds(userId);
        if (followedUserIds.isEmpty()) {
            return gson.toJson("{\"status\":\"error\",\"message\":\"您尚未关注任何用户\"}");
        }

        int offset = (pageNum - 1) * pageSize;
        List<User> users = userMapper.getUsersByIDs(followedUserIds, offset, pageSize);
        int total = userMapper.getUserCountByIDs(followedUserIds);

        return gson.toJson("{"
                + "\"status\":\"success\","
                + "\"data\":" + gson.toJson(users) + ","
                + "\"total\":" + total + ","
                + "\"pageNum\":" + pageNum + ","
                + "\"pageSize\":" + pageSize
                + "}");
    }
    /**
     * 根据用户ID获取关注列表
     * @param userId 用户ID
     * @return 包含关注列表的JSON字符串
     */
    @Override
    public String getFollowslist(int userId) {
        List<FollowRelation> follows = followRelationMapper.findByFollowerID(userId);
        List<User> userList  =new ArrayList<>();
        for (FollowRelation follow : follows) {
            userList.add(userMapper.selectUserById(follow.getFollowedID()));
        }
        return gson.toJson(userList);
    }


}
